package com.birdy.util;

import com.alibaba.fastjson.JSONObject;
import com.birdy.con.AppConst;
import com.birdy.dto.Response;
import lombok.extern.slf4j.Slf4j;

import java.net.SocketTimeoutException;

/**
 * @author birdy
 * @date 2022/3/30 11:24 AM
 */
@Slf4j
public class AppHttpHelper {
    public Response getAppSessionKeyAndOpenid(String url) {
        Response response;
        try {
            HttpSender httpSender = new HttpSender();
            String json = httpSender.get(url);
            log.info("调用接口成功！{}", json);
            JSONObject data = JSONObject.parseObject(json);
            String sessionKey = data.getString(AppConst.KEY_SESSION_KEY);
            String openid = data.getString(AppConst.KEY_OPENID);
            if (sessionKey != null && openid != null) {
                response = Response.builder().res(Response.SUCCESS).msg("success")
                        .data(AppConst.KEY_SESSION_KEY, sessionKey)
                        .data(AppConst.KEY_OPENID, openid)
                        .build();
            } else if(data.containsKey(AppConst.ERR_MSG)) {
                log.error("微信接口请求失败，请求结果是: {}", json);
                response = Response.builder().res(Response.FAILED).msg(data.getString(AppConst.ERR_MSG)).build();
            }
            else {
                log.error("微信接口请求异常，请求结果是: {}", json);
                response = Response.builder().res(Response.FAILED).msg("微信接口请求异常").build();
            }
        }catch (SocketTimeoutException e) {
            log.error("请求超时！{}", e.getMessage());
            response = Response.builder().res(Response.FAILED).msg("请求超时！").build();

        } catch (Exception e) {
            log.error("http请求失败！{}", e.getMessage());
            response = Response.builder().res(Response.FAILED).msg("http请求失败！").build();
        }
        return response;
    }
}
